#! /usr/bin/env python
#import cgitb; cgitb.enable() # you should only uncomment this when debugging
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime
import urllib2

try:
        i=urllib2.urlopen("http://domain-of-machine-A/webcamsnap.jpg")
except:
        print 'Content-type: text/html\n'
        print '''<html>
<body>
<center>Real-time webcam is temporarily unavailable.<br><br>
<img src="closed.jpg"> 
<br><br>
Please come back and check this page later.
</center>
</body>
</html>''' # closed.jpg for downtime
else:
        f=open('webcam.jpg', 'w+')
        f.write(i.read())
        f.seek(0)
        s= 'PST %s-%s-%s %s:%s:%s' %( str(datetime.now().year)[2]+str(datetime.now().year)[3], datetime.now().month, datetime.now().day, datetime.now().hour, datetime.now().minute, datetime.now().second)
        im=Image.open(f)
        draw=ImageDraw.Draw(im)
        font = ImageFont.truetype('Verdana.ttf', 20) # You need Verdana.ttf font
        color= '#000000'
        draw.text((380, 450), s, font=font, fill=color)
        draw.text((10, 10), 'http://domain-of-machine-B/path/to/webcam/page/', font=font, fill=color)
        f.seek(0)
        im.save(f, "jpeg")
        f.close()
        print 'Content-type: text/html\n'
        print '''<html>
<HEAD> <META HTTP-EQUIV=REFRESH CONTENT=10> </HEAD>
<body>
<center>Real-time Webcam<br><br>
<img src="webcam.jpg">
<br><br>
Auto refresh in about every 10 seconds
</center>
</body>
</html>'''

